package com.enki.adminplatform.security;

import com.enki.adminplatform.common.Const;
import com.enki.adminplatform.common.ResultCodeEnum;
import com.enki.adminplatform.exception.CaptchaException;
import com.enki.adminplatform.exception.EnkiException;
import com.enki.adminplatform.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author yinyin
 * @create 2021/07/27 下午 4:49
 */
//图片验证码处校验
@Component
public class CaptchaFilter extends OncePerRequestFilter {

    @Autowired
    RedisUtil redisUtil;

     @Autowired
     LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String uri = httpServletRequest.getRequestURI();
        if (("/login").equals(uri) && httpServletRequest.getMethod().equals("POST")){
            try {
                //校验
                validatePic(httpServletRequest);
            }catch(CaptchaException e){
                loginFailureHandler.onAuthenticationFailure(httpServletRequest,httpServletResponse,e);
                throw new EnkiException(ResultCodeEnum.VALID_FAIL);
            }

        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }

    private void validatePic(HttpServletRequest request){
        String code = request.getParameter("shield");
        String key = request.getParameter("key");

        if (StringUtils.isBlank(code) || StringUtils.isBlank(key)){
            throw new CaptchaException("验证码错误");
        }
        if (!code.equals(redisUtil.hget(Const.CAPTCHA_KEY,key))){
            throw  new CaptchaException("验证码错误");
        }

        //用完即删
        redisUtil.hdel(Const.CAPTCHA_KEY,key);
    }



}
